// ============================================================================
// 自定义 TypeORM 日志器 - 避免 ansis 依赖
// ============================================================================

import { Logger as TypeOrmLogger, QueryRunner } from 'typeorm'
import { logger } from '@roasmax/logger'

/**
 * 自定义 TypeORM 日志器
 * 避免使用 ansis 包，防止打包时的依赖问题
 */
export class CustomTypeOrmLogger implements TypeOrmLogger {
  /**
   * 记录查询日志
   */
  logQuery(query: string, parameters?: any[], queryRunner?: QueryRunner): void {
    const sql = this.formatQuery(query, parameters)
  }

  /**
   * 记录查询错误
   */
  logQueryError(error: string | Error, query: string, parameters?: any[], queryRunner?: QueryRunner): void {
    const sql = this.formatQuery(query, parameters)
    const errorMessage = error instanceof Error ? error.message : error
    logger.error(`[TypeORM Query Error] ${errorMessage}`)
    logger.error(`[TypeORM Query] ${sql}`)
  }

  /**
   * 记录查询慢日志
   */
  logQuerySlow(time: number, query: string, parameters?: any[], queryRunner?: QueryRunner): void {
    const sql = this.formatQuery(query, parameters)
    logger.warn(`[TypeORM Slow Query] ${time}ms - ${sql}`)
  }

  /**
   * 记录模式构建日志
   */
  logSchemaBuild(message: string, queryRunner?: QueryRunner): void {
    // logger.info(`[TypeORM Schema] ${message}`)
  }

  /**
   * 记录迁移日志
   */
  logMigration(message: string, queryRunner?: QueryRunner): void {
    // logger.info(`[TypeORM Migration] ${message}`)
  }

  /**
   * 记录一般日志
   */
  log(level: 'log' | 'info' | 'warn', message: any, queryRunner?: QueryRunner): void {
    const logMessage = `[TypeORM] ${message}`
    
    switch (level) {
      case 'log':
      case 'info':
        logger.info(logMessage)
        break
      case 'warn':
        logger.warn(logMessage)
        break
      default:
        logger.info(logMessage)
    }
  }

  /**
   * 格式化查询语句
   */
  private formatQuery(query: string, parameters?: any[]): string {
    if (!parameters || parameters.length === 0) {
      return query
    }

    // 简单的参数替换，避免复杂的SQL高亮
    let formattedQuery = query
    parameters.forEach((param, index) => {
      const placeholder = `$${index + 1}`
      const value = typeof param === 'string' ? `'${param}'` : String(param)
      formattedQuery = formattedQuery.replace(placeholder, value)
    })

    return formattedQuery
  }
}
